import axios from 'axios'

interface baseDataType {
  [key: number]: string
}

/** 请求头, 数据类型 */
const reqDataType: baseDataType = {
  1: 'application/x-www-form-urlencoded;charset=UTF-8',
  2: 'application/json;charset=utf-8'
}

export const requests = axios.create({
  baseURL: '',
  timeout: 30000 // 请求超时时间
})

requests.interceptors.request.use(config => {

  return config
}, err => {
  console.log('错误信息', err)
})

requests.interceptors.response.use(
  response => {
    return response
  },
  err => {
    console.log('错误信息: -> ', err)
  }
)


// post 请求
export function post(api: string, data = {}, dataType = 1, params = {}) {
  return new Promise((resolve, reject) => {
    requests({
      url: api,
      data,
      params,
      method: 'post',
      headers: { 'Content-Type': reqDataType[dataType] }
    }).then(res => {
      resolve(res.data)
    }).catch(error => {
      reject(error)
    })
  })
}

// get 请求
export function get(api: string, data = {}, dataType = 1) {
  return new Promise((resolve, reject) => {
    requests({
      url: api,
      params: data,
      method: 'get',
      headers: { 'Content-Type': reqDataType[dataType] }
    }).then(res => {
      resolve(res.data)
    }).catch(error => {
      reject(error)
    })
  })
}

// 导出文件
export function saveFile({
  url = <string>'',
  method = <string> 'post',
  data = {},
  fileName = <string>'',
  dataType = <number>1,
  fileType = <string>''
}) {
  return new Promise(resolve => {
    requests({
      url,
      data,
      method,
      responseType: 'blob',
      headers: { 'Content-Type': reqDataType[dataType] }
    }).then(res => {
      const blob = new Blob([res.data], { type: fileType })

      const a = document.createElement('a')
      a.href = window.URL.createObjectURL(blob)
      a.download = fileName

      a.click()
      URL.revokeObjectURL(a.href)

      resolve(true)
    }).finally(() => {
      resolve(false)
    }).catch(() => {
      resolve(false)
    })
  })
}
